package study;

import java.util.*;

public class Permute {
    public static int[][] permute(int[] test) {
        Arrays.sort(test);
        List<List<Integer>> list = new ArrayList<>();
        List<Integer> arr = new ArrayList<>();
        Map map = new HashMap<>();
        traceBack(test, list, arr, (HashMap) map);
        int[][] ret = new int[list.size()][test.length];
        for (int i = 0; i < list.size(); i++) {
            for (int j = 0; j < test.length; j++) {
                ret[i][j] = list.get(i).get(j);
            }
        }
        return ret;
    }

    public static void traceBack(int[] numbs, List<List<Integer>> res, List<Integer> stat, HashMap map) {
        if (stat.size() == numbs.length) {
            res.add(new ArrayList<>(stat));
            return;
        }
        for (int i = 0; i < numbs.length; i++) {
            if (!map.containsKey(numbs[i])) {
                stat.add(numbs[i]);
                map.put(numbs[i], 1);
                traceBack(numbs, res, stat, map);
                map.remove(stat.get(stat.size() - 1));
                stat.remove(stat.size() - 1);
            }
        }
    }

    public static void main(String[] args) {
        int[] test = {1, 2, 3};
        int[][] ret = permute(test);
        for (int i = 0; i < ret.length; i++) {
            System.out.println(Arrays.toString(ret[i]));
        }
    }
}
